<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>vue3-escook</title>
  <link rel="stylesheet" href="./lib/style.css">
  <style>
    .box {
      width: 200px;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      text-shadow: 1px 1px 5px #efefef;
    }
  </style>
  <script type="importmap">
    {
      "imports" : {
        "vue": "./lib/vue-3.5.0.js"
      }
    }
  </script>
  <script type="module">
    // import { createApp, ref, watch, onWatcherCleanup } from 'vue'
    import { createApp, ref, watch } from 'vue'

    const app = createApp({
      setup() {
        const id = ref(1)
        const bgColor = ref('#666')

        // watch(id, () => {
        //   const ac = new AbortController()

        //   fetch('https://api.liulongbin.top/v1/color', { signal: ac.signal }).then(res => res.json()).then(res => {
        //     console.log(res)
        //     bgColor.value = res.data.color
        //   })

        //   onWatcherCleanup(() => ac.abort('Request abort.'))
        // })

        // watch(id, (newId, oldId, onCleanup) => {
        //   const ac = new AbortController()

        //   fetch('https://api.liulongbin.top/v1/color', { signal: ac.signal }).then(res => res.json()).then(res => {
        //     console.log(res)
        //     bgColor.value = res.data.color
        //   })

        //   onCleanup(() => ac.abort('Request abort.'))
        // })

        watch(id, async (newId, oldId, onCleanup) => {
          const ac = new AbortController()
          // 如果副作用函数中，用到了 async/await 这种异步的写法，
          // 那么，清理函数必须放到第一个 await 之前，否则无法生效。
          onCleanup(() => ac.abort('Request abort.'))

          const res = await fetch('https://api.liulongbin.top/v1/color', { signal: ac.signal })
          const result = await res.json()

          console.log(result)
          bgColor.value = result.data.color
        })

        return {
          id,
          bgColor
        }
      }
    })

    app.mount('#app')
  </script>
</head>

<body>
  <div id="app">
    <button @click="id++">id +1</button>
    <hr>
    <div class="box" :style="{'background-color': bgColor}">{{ id }}</div>
  </div>
</body>

</html>